//
//  smcJaikuAPI+finishedDownloads.m
//  juhu
//
//  Created by Christian Martick on 26.07.07.
//  Copyright 2007 Christian Martick. All rights reserved.
//
//	jaiku api - recent posts of all jaiku users - public timeline sort of
//
//	this objects handle the users contacts posts using rss feed
//
//	Copyright (C) 2007 Christian Martick, http://juhu-mac.blogspot.com
//
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.

#import "smcJaikuAPI.h"

@implementation smcJaikuAPI (finishedDownloads)

/* 
	smcAsyncConnection delegates
	all finished asynchronous downloads end up here
	decide what todo depending on info
*/

- (void) downloadFromURL: (NSURL *) url didFinishWithData: (NSData *) data andInfo: (id) info
{
	// a download just finished, finding out what kind of download
	if ([[info objectForKey: @"kind"] isEqualTo: @"contactUpdate"])
	{
		// contact update finished successfully
		// create dict from data
		NSString *tmp = [NSString stringWithString: [self makeCleanUTF8MutableStringFromData: data]];
		
		NSDictionary *dict = [NSDictionary dictionaryWithJSONString: tmp];
		if (dict != nil)
		{
			if ([dict objectForKey: @"contacts"] != nil)
			{
				//okay, put it to contacts
				[_contacts release];
				_contacts = [[NSArray arrayWithArray: [dict objectForKey: @"contacts"]] retain];
				_contactUpdateError = NO;
			} else
				_contactUpdateError = YES;
		}else
			_contactUpdateError = YES;	
		_doingContactUpdate = NO;
	} else if ([[info objectForKey: @"kind"] isEqualTo: @"feedcatch"])
	{
		//stream download successfull
		//do post process
		[self _streamProcessingForStream: [info objectForKey: @"stream"] withData: data];
	} 
	else if ([[info objectForKey: @"kind"] isEqualToString: @"imagecatch"])
	{
		//an image, add it using info->number and decrease counter for images to do, if zero call delegate
	
		NSImage *img = [[[NSImage alloc] initWithData: data] autorelease];
		if (img != nil)
		{
			[img setScalesWhenResized: YES];
			[img setSize: NSMakeSize(34, 34)];
			[img lockFocus];
			[img unlockFocus];
			
			[_userImages setObject: img forKey: [info objectForKey: @"nick"]];
		}
		else
			[_userImages setObject: [NSImage imageNamed: @"avatar"] forKey: [info objectForKey: @"nick"]];
	
		_imagesStillToCatch--;
		
		[self _checkIfAllDoneForStream: [info objectForKey: @"stream"]];
	} 
	else if ([[info objectForKey: @"kind"] isEqualToString: @"flickrcatch"])
	{
		//get the flickr url from feed and add it
		[self _flickrAddURLForStream: [info objectForKey: @"stream"] withData: data andNumber: [[info objectForKey: @"number"] intValue]];
		_flickrStillToCatch--;				
		[self _checkIfAllDoneForStream: [info objectForKey: @"stream"]];
	}
	else if ([[info objectForKey: @"kind"] isEqualToString: @"threadcatch"])
	{
		[self processThreadFeedData: data fromUser: [info objectForKey: @"nick"] andID: [info objectForKey: @"ID"]];
	}
}

- (void) downloadFromURL: (NSURL *) url didFailWithError: (NSError *) error andInfo: (id) info
{
	// a download just failed, finding out what kind of download
	if ([[info objectForKey: @"kind"] isEqualTo: @"contactUpdate"])
	{
		// contact update failed successfully
		// its no core functionality, so if error, well then there it goes, just set error flag
		_contactUpdateError = YES;
		_doingContactUpdate = NO;
	} 
	else if ([[info objectForKey: @"kind"] isEqualTo: @"feedcatch"])
	{
		//stream feed fetch failed
		_doingUpdate = NO;
		[[self delegate] streamUpdateFailedWithError:
				[NSError errorWithDomain: @"streamUpdate"
					code: [error code] userInfo: [NSDictionary dictionaryWithObjectsAndKeys: 
						@"Could not update stream", @"errorAbstract",
						@"Your computer seems to be offline.", @"errorText", NULL]]];
		
	}	
	else if ([[info objectForKey: @"kind"] isEqualToString: @"imagecatch"])
	{
		//image catch failed, but remember _> the feed is caught successfully, because otherwise this
		//method wouldnt be called in the first place just put generic image in dict and decrease image count, if zero, post done...
		[[[_streams objectForKey: [info objectForKey: @"stream"]] objectAtIndex: [[info objectForKey: @"number"] intValue]] 
			setObject: [NSImage imageNamed: @"avatar"] forKey: kSmcEntryKeyUserImage];
		
		_imagesStillToCatch--;
		[self _checkIfAllDoneForStream: [info objectForKey: @"stream"]];
	} 
	else if ([[info objectForKey: @"kind"] isEqualToString: @"flickrcatch"])
	{
		//okay no json here, so nothing todo at all
		_flickrStillToCatch--;	
		[self _checkIfAllDoneForStream: [info objectForKey: @"stream"]];
	} 
}
@end
